<template>
  <div class="el-scroll-box">
    <el-scrollbar>
      <div class="course-body">
        <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-top:10px">
          <el-breadcrumb-item v-for="item in breadcrumbList" :key="item.text" :to="{ name: item.name, params: item.params }">{{ item.text }}</el-breadcrumb-item>
          <el-breadcrumb-item>{{ courseForm.name }}</el-breadcrumb-item>
        </el-breadcrumb>
        <el-row :gutter="10" style="margin-top:10px">
          <el-col :span="18">
            <div class="course-mask">
              <div class="couse-info">
                <h3 :title="courseForm.name">
                  {{ courseForm.name }}
                  <span>{{ courseForm.videoCount }}课时  </span><!--207人参加学习-->
                </h3>
              </div>
              <template v-if="courseForm.enable==1">
                <div v-if="courseForm.startEnable==0" class="join-btn" @click="joinStudy">
                  <button>加入学习</button>
                </div>
                <div v-else class="join-btn" @click="openComment">
                  <button>评价</button>
                </div>
              </template>

            </div>
            <el-tabs v-model="activeName">
              <el-tab-pane label="课程介绍" name="1">
                <div class="course-introduction">
                  <div class="course-info">
                    <div class="course-info-left" />
                    <div class="course-info-right">
                      <div class="course-label">适用人群</div>
                      <p v-html="courseForm.usesTo" />
                    </div>
                  </div>
                  <div class="course-info">
                    <div class="course-info-left" />
                    <div class="course-info-right">
                      <div class="course-label">课程概述</div>
                      <p v-html="courseForm.remark" />
                    </div>
                  </div>
                  <div class="course-info">
                    <div class="course-info-left" />
                    <div class="course-info-right">
                      <div class="course-label">课程目标</div>
                      <p v-html="courseForm.target" />
                    </div>
                  </div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="课程安排" name="2">
                <el-collapse v-if="courseForm.bookList.length" v-model="activeNames">
                  <el-collapse-item v-for="item in courseForm.bookList" :key="item.listid" :name="item.listid">
                    <template slot="title">
                      <span class="col-title">
                        <i class="header-icon el-icon-s-grid" />{{ item.name }}
                      </span>
                    </template>
                    <ul class="video-ul">
                      <li v-for="it in item.nodes" :key="it.detailid" @click="toPlayVideo(it)">
                        <div class="li-left">
                          <div class="study-circle">
                            <div class="inner-white" />
                          </div>
                          <span>{{ it.name }}</span>
                        </div>
                        <div class="li-right">
                          <span>{{ it.fileTime }}</span>
                          <svg-icon icon-class="icon-video" />
                        </div>
                      </li>
                    </ul>
                  </el-collapse-item>
                </el-collapse>
                <!-- 暂无数据 -->
                <empty-data v-else text="暂无数据" />
              </el-tab-pane>
              <el-tab-pane label="课程评价" name="3">
                <div class="comment-info">
                  <div class="comment-left">
                    <span>{{ commentData.percent || 0 }}%</span>
                    <span>好评率</span>
                  </div>
                  <div class="comment-right">
                    <el-radio v-for="(item, key) in commentData.commentLevel" :key="key" v-model="commentData.commentType" :label="key">{{ key }}（{{ commentData.commentLevel[key].length }}）</el-radio>
                  </div>
                </div>
                <ul v-if="commentData.commentList.length" class="comment-ul">
                  <li v-for="item, i in commentData.commentList" :key="i">
                    <div class="avatar">
                      <img src="@/assets/user/default.jpg" alt="">
                    </div>
                    <div class="comment-wrapper">
                      <div class="avatar-name">
                        {{ item.userName }}
                        <span>
                          <svg-icon icon-class="icon-shijian" style="margin-right:5px" />
                          {{ item.createTime }}
                        </span>
                      </div>
                      <div>{{ item.remark }}</div>
                      <div class="score-del-wrapper">
                        <el-rate
                          v-model="item.score"
                          disabled
                          score-template="{value}"
                        />
                        <span v-if="item.candelSelftComment" class="command" @click="removeReply(item)">
                          <i style="font-size: 20px;cursor: pointer" class="el-icon-delete" />
                          <span>删除</span>
                        </span>
                      </div>
                    </div>
                  </li>
                </ul>
                <!-- 暂无数据 -->
                <empty-data v-else text="暂无评价" />
              </el-tab-pane>
            </el-tabs>
          </el-col>
          <el-col :span="6">
            <el-card :body-style="{ padding: '10px', textAlign:'center' }">
              <el-progress type="circle" :percentage="courseForm.precent || 0" :stroke-width="20" />
              <p><i class="el-icon-success" :style="{'color': courseForm.precent>0?'rgb(32,160,255)':'#333'}" /> 已学习</p>
              <!-- <p>{{ courseForm.posCount }} / {{ courseForm.bookCount }} 课时</p> -->
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-scrollbar>

    <!-- 评价 -->
    <el-dialog
      title="评价"
      :visible.sync="commentParams.visible"
      width="500px"
    >
      <el-form ref="form" :model="commentParams.commentInfoForm" label-width="40px">
        <el-form-item label="评分">
          <el-rate v-model="commentParams.commentInfoForm.score" />
        </el-form-item>
        <el-form-item label="评价">
          <el-input
            ref="commentInfoFormRemark"
            v-model="commentParams.commentInfoForm.remark"
            type="textarea"
            :rows="2"
            :maxlength="50"
            show-word-limit
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="commentParams.confirm">确 定</el-button>
        <el-button @click="commentParams.visible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getLearnBook, startLearnBook, getScroeLearnBook, scroeLearnBook, getScroeLearnBookList, delScroeLearnBook } from '@/api/learnCenter'
import EmptyData from '@/components/EmptyData'
import { formatSeconds } from '@/utils'
export default {
  name: 'CourseBody',
  components: {
    EmptyData
  },
  data() {
    return {
      activeName: '1',
      activeNames: ['1'],
      radio: '1',
      value: 5,
      courseForm: {
        name: '',
        remark: '',
        target: '',
        usesTo: '',
        picFile: '',
        startLearn: '',
        schoolHour: 0, // 课时
        bookList: [] // 课程列表
      },
      commentData: {
        commentType: '全部评价',
        percent: 0,
        commentList: [], // 显示评论列表
        allCommentList: [], // 全部评论列表
        commentLevel: { // 好中差评价
          '全部评价': [],
          '好评': [],
          '中评': [],
          '差评': []
        },
        canDelReply: false // 是否可删除评论
      },
      commentParams: {
        visible: false,
        commentInfoForm: {
          id: '',
          score: 0,
          remark: ''
        },
        confirm: () => {}
      },
      breadcrumbList: []
    }
  },
  watch: {
    'commentData.commentType'(val) {
      switch (val) {
        case '全部评价':
          this.commentData.commentList = this.commentData.allCommentList
          break
        case '好评':
          this.commentData.commentList = this.commentData.allCommentList.filter(item => item.score >= 5)
          break
        case '中评':
          this.commentData.commentList = this.commentData.allCommentList.filter(item => (item.score >= 3 && item.score < 5))
          break
        case '差评':
          this.commentData.commentList = this.commentData.allCommentList.filter(item => (item.score >= 0 && item.score < 3))
          break
      }
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if ((from.name === 'LearnCenter') || (from.name === 'StudyLine')) {
        Object.assign(vm.$data, vm.$options.data.call(vm))
      }
      // 面包屑
      const breadcrumbList = []
      if (from.name === 'PlayVideo') {
        breadcrumbList.push({
          name: 'LearnCenter',
          text: '课程中心',
          params: {}
        })
      } else {
        breadcrumbList.push({
          name: from.name,
          text: from.meta.title,
          params: from.params
        })
      }

      vm.breadcrumbList = breadcrumbList

      // 刷新回显面包屑
      if (from.name) {
        window.sessionStorage.setItem('breadcrumbList', JSON.stringify(breadcrumbList))
      } else {
        const breadcrumbList = window.sessionStorage.getItem('breadcrumbList')
        if (breadcrumbList) {
          vm.breadcrumbList = JSON.parse(breadcrumbList)
        }
      }
    })
  },
  activated() {
    setTimeout(() => {
      this.getCourseInfo()
      setTimeout(() => {
        this.getPrecentPre()
      }, 1000)
    }, 500)
    this.getComment()
  },
  methods: {
    // 课程详情
    getCourseInfo() {
      const vPar = new this.ParamArr()
      vPar.setStr('ID', this.$route.params.id)
      getLearnBook(vPar).then(vPar => {
        // console.log('getLearnBook')
        // console.log(vPar)
        this.courseForm.name = vPar.getStr('Name')
        this.courseForm.remark = vPar.getStr('Remark')
        this.courseForm.target = vPar.getStr('Target')
        this.courseForm.groupIDs = vPar.getStr('GroupIDs').split(',')
        this.courseForm.tagIDs = vPar.getStr('TagIDs').split(',')
        this.courseForm.usesTo = vPar.getStr('UsesTo')
        this.courseForm.picFile = vPar.getStr('PicFile')
        this.courseForm.startTime = vPar.getStr('StartTime')
        this.courseForm.startEnable = vPar.getInt('StartEnable')
        this.courseForm.enable = vPar.getInt('Enable')
        // 视频 (总课时、时长、视频数)
        this.courseForm.bookCount = vPar.getInt('BookCount')
        this.courseForm.bookTime = vPar.getInt('BookTime')
        this.courseForm.videoCount = vPar.getInt('VideoCount')
        // 已学习 (课时、时长、视频数)
        this.courseForm.posCount = vPar.getInt('PosCount')
        this.courseForm.posTime = vPar.getInt('PosTime')
        this.courseForm.posVideo = vPar.getInt('PosVideo')
        this.courseForm.precent = Math.floor((this.courseForm.posTime / this.courseForm.bookTime) * 100) >= 98 ? 100 : Math.floor((this.courseForm.posTime / this.courseForm.bookTime) * 100)
        const bookList = []
        // 获取章节
        this.getBookList(vPar, bookList)
      })
    },
    // 获取进度
    getPrecentPre() {
      const vPar = new this.ParamArr()
      vPar.setStr('ID', this.$route.params.id)
      getLearnBook(vPar).then(vPar => {
        // 视频 (总课时、时长、视频数)
        this.courseForm.bookTime = vPar.getInt('BookTime')
        // 已学习 (课时、时长、视频数)
        this.courseForm.posTime = vPar.getInt('PosTime')
        this.courseForm.precent = Math.floor((this.courseForm.posTime / this.courseForm.bookTime) * 100) >= 98 ? 100 : Math.floor((this.courseForm.posTime / this.courseForm.bookTime) * 100)
      })
    },
    // 获取章节列表
    getBookList(vPar, bookList) {
      const nodes = []
      const table = new this.SQLTable(vPar.getTable('k_learn_book_list'))
      table.first()
      while (!table.eof()) {
        const node = {}
        node['listid'] = table.getValueByName('ListID')
        node['bookid'] = table.getValueByName('BookID')
        node['text'] = table.getValueByName('Name')
        node['name'] = table.getValueByName('Name')
        node['remark'] = table.getValueByName('Remark')
        node['icon'] = 'icon-wenbenmoban'
        nodes.push(node)
        table.next()
      }
      bookList = [...bookList, ...nodes]
      // 获取章节视频
      this.getVideoList(vPar, bookList)
    },
    // 获取章节视频
    getVideoList(vPar, bookList) {
      const nodes = []
      const table = new this.SQLTable(vPar.getTable('k_learn_book_detail'))
      table.first()
      while (!table.eof()) {
        const node = {}
        node['detailid'] = table.getValueByName('DetailID')
        node['listid'] = table.getValueByName('ListID')
        node['bookid'] = table.getValueByName('BookID')
        node['name'] = table.getValueByName('Name')
        node['filePath'] = table.getValueByName('FilePath')
        node['fileName'] = table.getValueByName('FileName')
        node['fileTime'] = formatSeconds(table.getValueByName('FileTime'))
        nodes.push(node)
        table.next()
      }

      bookList.forEach(it1 => {
        nodes.forEach(it2 => {
          if (it1.listid === it2.listid) {
            if (it1.nodes) {
              it1.nodes.push(it2)
            } else {
              it1.nodes = [it2]
            }
          }
        })
      })

      this.courseForm.bookList = bookList
      bookList.length && (this.activeNames = [bookList[0].listid]) // 展开第一页
    },
    // 获取课程评论
    getComment() {
      const vPar = new this.ParamArr()
      vPar.setStr('ID', this.$route.params.id)
      const userID = this.$store.state.user.name
      getScroeLearnBookList(vPar).then(vPar => {
        // console.log(vPar)
        this.commentData.canDelReply = vPar.getBool('CanDelReply') || false // 是否可删除评论
        const nodes = []
        const table = new this.SQLTable(vPar.getTable('k_learn_book_score'))
        table.first()
        while (!table.eof()) {
          const node = {}
          node['id'] = table.getValueByName('ID')
          node['userID'] = table.getValueByName('UserID')
          node['userName'] = table.getValueByName('UserName')
          node['score'] = parseInt(table.getValueByName('Score'))
          node['remark'] = table.getValueByName('Remark')
          node['createTime'] = table.getValueByName('CreateTime')
          if (this.commentData.canDelReply) {
            node['candelSelftComment'] = true
          } else {
            if (userID === node['userID']) {
              node['candelSelftComment'] = true
            }
          }
          nodes.push(node)
          table.next()
        }
        // console.log(nodes)
        this.commentData.commentList = nodes
        this.commentData.allCommentList = nodes

        const commentLevel = {
          '全部评价': [],
          '好评': [],
          '中评': [],
          '差评': []
        }
        this.commentData.allCommentList.forEach(item => {
          commentLevel['全部评价'].push(item)
          switch (item.score) {
            case 0:
            case 1:
              commentLevel['差评'].push(item)
              break
            case 2:
            case 3:
              commentLevel['中评'].push(item)
              break
            case 4:
            case 5:
              commentLevel['好评'].push(item)
              break
          }
        })
        this.commentData.commentLevel = commentLevel
        this.commentData.percent = Math.ceil((commentLevel['好评'].length / commentLevel['全部评价'].length) * 100)
      })
    },
    // 加入课时
    joinStudy() {
      const vPar = new this.ParamArr()
      vPar.setStr('ID', this.$route.params.id)
      startLearnBook(vPar).then(vPar => {
        this.getCourseInfo()
      })
    },
    // 打开评论弹框
    openComment() {
      // 获取上次评价内容
      const vPar = new this.ParamArr()
      vPar.setStr('ID', this.$route.params.id)
      getScroeLearnBook(vPar).then(vPar => {
        // this.commentParams.commentInfoForm = {
        //   id: this.$route.params.id,
        //   score: vPar.getInt('Score'),
        //   remark: vPar.getStr('Remark')
        // }
        this.commentParams.visible = true
        this.commentParams.commentInfoForm = {
          id: '',
          score: 0,
          remark: ''
        }
        this.commentParams.visible = true
        this.commentParams.confirm = () => {
          const commentInfoForm = this.commentParams.commentInfoForm
          if (!commentInfoForm.remark) {
            this.$refs.commentInfoFormRemark.focus()
            return this.$message.warning('请输入评价')
          }
          const vPar = new this.ParamArr()
          vPar.setStr('ID', this.$route.params.id)
          vPar.setInt('Score', commentInfoForm.score)
          vPar.setStr('Remark', commentInfoForm.remark)
          scroeLearnBook(vPar).then(vPar => {
            this.commentParams.visible = false
            this.getComment()
          })
        }
      })
    },
    // 播放视频
    toPlayVideo(item) {
      if (this.courseForm.startEnable == 0) return this.$message.warning('请先加入学习')
      this.$openUrl('PlayVideo', '', {
        detailid: item.detailid,
        listid: item.listid,
        bookid: item.bookid
      }, {
        id: item.detailid
      })
    },
    // 删除评论
    removeReply(item) {
      this.$comfirmDialog({
        message: `是否确认删除?`,
        confirm: () => {
          const vPar = new this.ParamArr()
          vPar.setStr('ID', item.id)
          delScroeLearnBook(vPar).then(vPar => {
            this.getComment()
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-scrollbar__wrap {
  overflow-x: hidden;
}
.el-scroll-box {
  width: 100%;
  height: 100%;
  background-image: url('../../../assets/user/Main_bg.png');
  background-size: 100%;
  background-repeat: no-repeat;
  .el-scrollbar {
    height:100%
  }
}
.course-body {
  width: 80%;
  margin: 0 auto;
}
.course-mask {
  padding: 20px;
  height: 150px;
  background-color: #B3C0D1;
  margin-bottom: 20px;
  background-image: url('../../../assets/user/learnCenter_bg.png');
  background-repeat: no-repeat;
  background-size:100% 150px;
  .couse-info {
    margin-right: 20px;
    h3 {
      font-size: 24px;
      line-height: 30px;
      color: #333333;
      display: -webkit-box; /* 盒子类型 */
      word-break: break-all; /* 自动换行的处理方法。允许在单词内换行 */
      text-overflow: ellipsis; /* 溢出时用... */
      overflow: hidden;
      -webkit-box-orient: vertical;
      -webkit-line-clamp:2; /* 行数 */
      span {
        font-size: 14px;
        color: #5b5b5b;
      }
    }
  }
}
.join-btn {
  display: flex;
  align-items: center;
  button {
    margin-left: 5px;
    width: 120px;
    height: 30px;
    border: none;
    border-radius: 5px;
    box-shadow: none;
    font-size: 13px;
    font-weight: 400;
    color: #fff;
    cursor: pointer;
    background-color: $primaryColor;
    border-radius: 2px;
  }
}
::v-deep .el-tabs .el-tabs__item {
  font-size: 16px;
  font-weight: bold;
}
.course-info {
  display: flex;
  margin-bottom: 20px;
  .course-info-left {
    width: 15px;
    height: 15px;
    background-color: $primaryColor;
    margin-right: 5px;
  }
  .course-info-right {
    .course-label {
      line-height: 15px;
    }
    p {
      font-size: 14px;
      color: #555;
    }
  }
}
.col-title {
  color: #9A9C9C;
  font-weight: 700;
  font-size: 14px;
  padding-left: 15px;
  color: $primaryColor;
  i {
    margin-right: 10px;
  }
}
.video-ul {
  padding-left: 5px;
  li {
    display: flex;
    align-items: center;
    justify-content: space-between;
    cursor: pointer;
    padding: 10px;
    font-size: 13px;
    &:hover {
      background-color: $infoColor;
    }
    .li-left {
      display: flex;
      align-items: center;
      .study-circle {
        width: 15px;
        height: 15px;
        border-radius: 50%;
        border: 2px solid $plainColor;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 10px;
        .inner-white {
          width: 9px;
          height: 9px;
          background-color: #fff;
          border-radius: 50%;
        }
      }
    }
    .li-right {
      span {
        margin-right: 10px;
      }
    }

  }
}

.comment-info {
  // height: 65px;
  background-color: rgba(245, 245, 245, 1);
  display: flex;
  .comment-left {
    border-right: 1px solid #e4e4e4;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 10px;
    span:first-child {
      font-weight: 700;
      font-style: normal;
      font-size: 16px;
      color: $primaryColor;
      margin-bottom: 5px;
    }
    span:nth-child(2){
      font-size: 13px;
    }
  }
  .comment-right {
    display: flex;
    align-items: center;
    padding: 10px;
  }
}
.comment-ul {
  padding-left: 0;
  li {
    display: flex;
    border-bottom: 1px solid #ccc;
    padding: 10px 10px 0;
    .avatar {
      margin-right: 10px;
      img {
        width: 24px;
        height: 24px;
        object-fit: cover;
        border-radius: 2px;
      }
    }
    .comment-wrapper {
      font-size: 14px;
      flex-grow: 1;
      .avatar-name {
        color: #8590a6;
        line-height: 24px;
        font-size: 14px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        span {
          font-size: 13px;
        }
      }
      >div:nth-child(2) {
        line-height: 25px;
      }
    }
  }
}
::v-deep .el-collapse-item__content {
  padding-bottom: 0;
}
.score-del-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  line-height: 20px;
  font-size: 12px;
  cursor: pointer;
  color: #86909c;
  &:hover {
    color: #1989fa;
  }
}
</style>
